/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import ContentManagers.Models.AccountingManager;
import ContentManagers.RoleManagers.AdminManager;
import ContentManagers.Security.Hasher;
import ContentManagers.Security.Validator;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ervin James
 */
@WebServlet(name = "ServletAddAM", urlPatterns = {"/ServletAddAM"})
public class ServletAddAM extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            boolean checker=false;
            AccountingManager am = new AccountingManager();
            AdminManager adminManager = new AdminManager();
            String username = Validator.inputSanitizer(request.getParameter("username"));
            String password = Validator.passwordSanitizer(request.getParameter("password"));
            String password2 = Validator.passwordSanitizer(request.getParameter("password2"));
            HttpSession session = request.getSession();
            
          if(username.isEmpty() || username.length()>45) {
            WebLogger.insertLog(request.getRemoteAddr().toString(), request.getHeader("referer"), request.getRequestURI().toString(),"Invalid username "+username+ " entered.",false);
            session.setAttribute("m2", "1");
            response.sendRedirect("./Admin Interface/admin_index.jsp");
          }
          else if (!password.equals(password2) || password.isEmpty() || password.length()>100) {
            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Invalid password entered.",false);  
            session.setAttribute("m2", "2");  
            response.sendRedirect("./Admin Interface/admin_index.jsp"); 
          }
          else if (adminManager.checkAccountingManager(am)) {
            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Invalid username "+username+" entered. Account already exist.",false);
            session.setAttribute("m2", "3");  
            response.sendRedirect("./Admin Interface/admin_index.jsp");
          }
          else{
              
            String tempPassword[] = new String[2];
            tempPassword = Hasher.processPassword(password);
            am.setUsername(username);
            am.setPassword(tempPassword[0]);
            am.setPasswordSalt(tempPassword[1]);
            am.setTimeStamp();
          
            checker=adminManager.addAccountingManager(am);
            
            if(checker==true)
            {
                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Account "+username+" was successfully added.",true);
                session.setAttribute("m2", "5");
                response.sendRedirect("./Admin Interface/admin_index.jsp");
            }
            else
            {
                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Failed to add "+username,false);
                session.setAttribute("m2", "4");
                response.sendRedirect("./Admin Interface/admin_index.jsp");
            }
          }
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
